package main

import (
    "fmt"
    "net"
    "time"
)

func startMaster() {
    listener, err := net.Listen("tcp", config.MasterAddr)
    if err != nil {
        fmt.Println("Error starting master:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Master started on", config.MasterAddr)

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting connection:", err)
            continue
        }
        go handleMasterConnection(conn)
    }
}

func handleMasterConnection(conn net.Conn) {
    defer conn.Close()

    for {
        message, err := receiveIEC104Message(conn)
        if err != nil {
            fmt.Println("Error receiving message:", err)
            return
        }

        if !verifyAuthKey(message.Data, config.AuthKey, message.AuthKey) {
            fmt.Println("Authentication failed")
            return
        }

        switch message.Type {
        case "C":
            fmt.Println("Data call:", message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "R", Data: "01", AuthKey: generateAuthKey("01", config.AuthKey)})
        case "R":
            fmt.Println("Remote control:", message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "A", Data: "02", AuthKey: generateAuthKey("02", config.AuthKey)})
        case "A":
            fmt.Println("Remote adjustment:", message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "S", Data: "03", AuthKey: generateAuthKey("03", config.AuthKey)})
        case "S":
            fmt.Println("Remote signal:", message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "M", Data: "04", AuthKey: generateAuthKey("04", config.AuthKey)})
        case "M":
            fmt.Println("Remote measurement:", message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "F", Data: "05", AuthKey: generateAuthKey("05", config.AuthKey)})
        default:
            fmt.Println("Unknown message type:", message.Type)
        }
    }
}